<template>
  <div class="container">
    <div
      class="box"
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
    >
      悬浮
    </div>
  </div>
</template>

<script>
export default {
  name: 'Drag',
  data() {
    return {
      touchX: 0, //移动端点击时距左边的距离
      touchY: 0,
      odiv: {},
    }
  },
  methods: {
    //手指按下
    touchStart(e) {
      e.preventDefault()
      this.odiv = e.target //获取目标元素
      //算出鼠标相对元素的位置
      this.touchX = e.changedTouches[0].pageX - this.odiv.offsetLeft
      this.touchY = e.changedTouches[0].pageY - this.odiv.offsetTop
      console.log('x======' + this.touchX, 'y======' + this.touchY)
      console.log(
        'offsetLeft======' + this.odiv.offsetLeft,
        'offsetTop======' + this.odiv.offsetTop,
      )
      console.log(
        'innerWidth=====' + window.innerWidth,
        'innerHeight=====' + window.innerHeight,
      )
      console.log(this.odiv.offsetWidth, this.odiv.offsetHeight) //元素宽高
    },
    //手指拖动事件
    touchMove(e) {
      //用手指的位置减去手指相对元素的位置，得到元素的位置
      console.log(e.changedTouches)
      let left = e.changedTouches[0].pageX - this.touchX
      let top = e.changedTouches[0].pageY - this.touchY
      console.log('left======' + left, 'top======' + top)

      if (left < 0) {
        left = 0
      }
      if (left > window.innerWidth - this.odiv.offsetWidth) {
        left = window.innerWidth - this.odiv.offsetWidth
      } //可视区域宽度
      if (top < 0) {
        top = 0
      }
      if (top > window.innerHeight - this.odiv.offsetHeight) {
        top = window.innerHeight - this.odiv.offsetHeight
      } //可视区域高度

      //移动当前元素
      this.odiv.style.left = left + 'px'
      this.odiv.style.top = top + 'px'
    },
    //手指抬起
    touchEnd() {
      console.log(123)
    },
  },
}
</script>
<style lang="less" scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-image: linear-gradient(180deg, #7ccff1 5%, #0a8233 100%);
  .box {
    position: absolute; /*定位*/
    top: 30px;
    left: 30px;
    width: 80px;
    height: 80px;
    background: rgb(0, 255, 234); /*设置一下背景*/
    z-index: 999;
    border-radius: 50%;
    font-size: 0.15rem;
    line-height: 80px;
    text-align: center;
  }
}
</style>
